package ipc

import (
	"github.com/golang/protobuf/proto"
	"github.com/name5566/leaf/log"
)

// 消息传输体
type Request struct {
	Uid int32
	Cmd uint16
	Param proto.Message
	AskBack bool    // 要求返回
}

type Response struct {
	Code string
	Body string
}

type IIpcServer interface {
	IpcName() string
	IpcHandle(uid int32, cmd uint16, pbMsg proto.Message) error
}

type IpcServer struct {
	IIpcServer
}

func NewIpcServer(s IIpcServer) *IpcServer {
	return &IpcServer{s}
}

func (server *IpcServer) Connect() (chan Request, chan error) {
	session := make(chan Request, 0)
	back := make(chan error, 0)

	go func(c chan Request, b chan error) {
		for {
			req := <-c

			if req.Cmd == 0 {
				break
			}

			//var req Request
			//err := json.Unmarshal([]byte(request), &req)
			//if err != nil {
			//	log.Debug("invalid request format:%s", request)
			//}

			err := server.IpcHandle(req.Uid, req.Cmd, req.Param)
			if req.AskBack {
				b <- err
			}
			//b, err := json.Marshal(resp)

			//c <- string(b)
		}
		log.Debug("Session closed.")

	} (session, back)

	return session, back
}